<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou\fetch;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\service\fetch\KuaiShouFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class VideoCreativeNumWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_KEY]['mongo_video_creative_num'];

    protected function configure()
    {
        // 指令配置
        $this->setName('ks_video_creative_num_work');
        $this->setDescription('拉取快手视频关联创意数');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('拉取快手视频关联创意数开始');
        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            try {
                $advertiserId = $redis->lPop(self::REDIS_TASK_KEY);
                if (! $advertiserId) {
                    $this->getOutputMessage('暂无数据');
                    sleep(rand(5, 10));
                    continue;
                }

                $this->getOutputMessage('拉取账户[' . $advertiserId . ']开始');
                if (! KuaiShouFetchService::fetchMongoVideoCreativeNum($advertiserId)) {
                    $this->getOutputMessage('拉取账户[' . $advertiserId . ']失败:' . KuaiShouFetchService::getError(0));
                }
                $this->getOutputMessage('拉取账户[' . $advertiserId . ']结束');
            } catch (\Exception $e) {
                $this->getOutputMessage('错误：' . $e->getMessage());
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
            }
        }
        $this->getOutputMessage('拉取快手视频关联创意数结束');
    }
}
